// pages/feedback/feedback.js
import request from './../../utils/request';
const app = getApp<IAppOption>();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    description: '',
    phone: '',
    imgSrc: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {},

  selectImage() {
    wx.chooseMedia({
      count: 1,
      sizeType: ['compressed'],
      mediaType: ['image'],
      success: (res) => {
        const path = res.tempFiles[0].tempFilePath;
        this.setData({
          imgSrc: path
        });
      },
      fail: () => {
        wx.showToast({
          icon: 'error',
          title: '无法打开本地相册！'
        });
      }
    });
  },

  handleInputDesc(event: any) {
    const text = event.detail.value;
    this.setData({
      description: text
    });
  },

  handleInputPhone(event: any) {
    const text = event.detail.value;
    this.setData({
      phone: text
    });
  },

  uploadFile() {
    return new Promise<string>((resolve, reject) => {
      wx.uploadFile({
        url: app.globalData.baseUrl + '/base/upload',
        filePath: this.data.imgSrc,
        name: 'image',
        header: {
          'content-type': 'multipart/form-data',
          'role': 'client'
        },
        success: (res) => {
          resolve(res.data);
        },
        fail: (err) => {
          reject(err.errMsg);
        }
      });
    });
  },

  async submitInfo() {
    if (!this.data.description.trim()) {
      return void wx.showModal({
        title: '提交内容缺失',
        content: '问题和意见为必填内容！',
        showCancel: true
      });
    }
    if (!this.data.phone.trim()) {
      return void wx.showModal({
        title: '提交内容缺失',
        content: '手机号码为必填内容！',
        showCancel: true
      });
    }

    let paths: string[] = [];
    if (this.data.imgSrc) {
      const uploadResStr = await this.uploadFile();
      const { data } = JSON.parse(uploadResStr);
      paths = data;
    }

    const res = await request<string>({
      url: '/feedback/add',
      method: 'POST',
      data: {
        description: this.data.description,
        phone: this.data.phone,
        path: paths[0]
      }
    });

    if (res.code === 200) {
      wx.showToast({
        title: '反馈成功'
      });
      this.setData({
        description: '',
        phone: '',
        imgSrc: ''
      });
    }
  }
});

export {};
